<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      class="frominfo"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <div class="from-item">
        <el-form-item label="群用户名" prop="groupUserName">
          <el-input
            v-model="queryParams.groupUserName"
            @keyup.enter.native="handleQuery"
            placeholder="请输入微信名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="群聊名称" prop="wcGroupName">
          <el-input
            v-model="queryParams.wcGroupName"
            @keyup.enter.native="handleQuery"
            placeholder="请输入群聊名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="助手名称" prop="wcName" v-if="!common">
          <el-input
            v-model="queryParams.wcName"
            @keyup.enter.native="handleQuery"
            placeholder="请输入助手名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="活跃度" prop="liveLevel">
          <el-select
            v-model="queryParams.liveLevel"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_active_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="from-Btn">
        <el-form-item>
          <el-button
            class="blue-button"
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          class="blue-button"
          plain
          icon="el-icon-folder-add"
          size="mini"
          @click="handleAdd"
          >批量添加</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      ref="multipleTable"
      :header-cell-style="{ background: '#fcfcfd', color: '#000' }"
      :border="false"
      :data="wcGroupsUserList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="微信名称"
        prop="groupUserName"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="所在群名"
        prop="wcGroupName"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="活跃度"
        prop="liveLevel"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_active_level"
            :value="scope.row.liveLevel"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="同群营销助手"
        prop="nickName"
        align="center"
        :show-overflow-tooltip="true"
      />true"/>
      <el-table-column
        label="最新群聊天时间"
        prop="lastChatTime"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastChatTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label=""
        align="center"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template slot="header">
          <span>微信号操作</span>
          <el-tooltip
            class="item"
            effect="dark"
            content="点击添加好友"
            placement="top"
          >
            <i class="el-icon-warning" style="color: #818e96"></i>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            >加好友</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改微信群成员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <div class="dia-box">
        <span
          v-if="!common"
          style="font-size: 14px; margin-right: 10px; line-height: 40px"
          >请选择营销助手</span
        >
        <div class="dia-box-search" v-if="!common">
          <div class="select-all">
            <i class="el-icon-arrow-right" style="margin-right: 10px"></i
            ><el-checkbox v-model="checkAll" @change="handleCheckAllChange"
              >全选</el-checkbox
            >
          </div>
          <div style="width: 260px">
            <el-input
              placeholder="请输入微信名称"
              v-model="query.wcName"
              class="input-with-select"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="search"
              ></el-button>
            </el-input>
          </div>
        </div>
        <span class="box-txt" style="color: red" v-if="show"
          >置灰助手不可选，添加好友超过最高限制</span
        >
        <div class="dia-box-lable" v-if="show">
          <div
            v-for="(item, index) in AssistList"
            :key="index"
            class="lable-box"
            @click="item.canCreateTask ? setIdx(index, item.remark) : goTs()"
            :style="
              item.canCreateTask
                ? item.remark
                  ? 'background-color: #0078fb;border-color: #0078fb;color: #fff;'
                  : ''
                : 'background-color: #dcdcdc;'
            "
          >
            {{ item.wcName }}
          </div>
        </div>
        <div class="dia-box-lable" v-if="!common">
          <span style="font-size: 14px; color: #9aa5aa">已选：</span>
          <div
            v-for="(item, index) in selectList"
            :key="index"
            class="lable-box"
          >
            {{ item.wcName
            }}<i
              @click="delIdx(index, item.wcId)"
              class="el-icon-close"
              style="margin-left: 10px"
            ></i>
          </div>
          <span v-if="selectList == '' || selectList == null">请选择选择</span>
        </div>
        <div class="dia-box-time">
          <div class="box-setups">
            <span style="margin-right: 10px"
              ><span style="color: #ff6d6f">*</span>申请好友用语</span
            >
            <el-autocomplete
              type="textarea"
              rows="4"
              :maxlength="460"
              class="my-autocomplete"
              v-model="addGroupFriend.applyContent"
              ref="autocomplete"
              :fetch-suggestions="querySearch"
              placeholder="请输入或选择内容"
              @select="handleSelect"
            >
              <template slot-scope="{ item }">
                <div class="name">{{ item.label }}</div>
              </template>
            </el-autocomplete>
          </div>
          <div class="box-setup">
            <span style="margin-right: 10px"
              ><span style="color: #ff6d6f">*</span>执行时间</span
            >
            <el-radio-group v-model="addGroupFriend.wcTimedTasks.executionType">
              <el-radio :label="1">立即执行</el-radio>
              <el-radio :label="2">定时执行</el-radio>
            </el-radio-group>
          </div>
          <div
            style="
              height: 10px;
              line-height: 10px;
              font-size: 12px;
              color: rgb(255, 109, 111);
              margin-bottom: 10px;
            "
          >
            任务只在早上7点到晚上9点之间执行
          </div>
          <div
            class="box-setup"
            v-if="addGroupFriend.wcTimedTasks.executionType == 2"
          >
            <span>定时：</span>
            <el-date-picker
              v-model="addGroupFriend.wcTimedTasks.satartDate"
              type="datetime"
              placeholder="选择日期时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              align="right"
            >
            </el-date-picker>
          </div>
          <!-- <div style="display: flex;align-items: center;">
                <span>单次间隔时间：</span>
                <el-select v-model="addGroupFriend.wcTimedTasks.intervalTime" placeholder="请选择" clearable>
                    <el-option v-for="dict in dict.type.sys_time_type" :key="dict.value" :label="dict.label+'ms'" :value="dict.label"/>
                </el-select>
            </div> -->
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

  <script>
import request from "@/utils/request";
import moment from "moment";
export default {
  name: "WcGroupsUser",
  dicts: ["sys_time_type", "sys_cycle_type", "sys_active_level"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 微信群成员表格数据
      wcGroupsUserList: [],
      // 弹出层标题
      title: "新增任务",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        wcId: null,
        deptId: null,
        addState: 0,
        groupUserName: null,
        wcGroupName: null,
        wcName: null,
        liveLevel: null,
      },
      show: false,
      common: false,
      query: {
        pageNum: 1,
        pageSize: 999,
        wcId: null,
        deptId: null,
        wcName: null,
        wcNumber: null,
        wcPhone: null,
      },
      radio: 0,
      totals: 0,
      checkAll: false,
      AssistList: [],
      selectList: [],
      chatTime: [],
      addGroupFriend: {
        wcUserInfoList: [],
        wcGroupsUserList: [],
        wcTimedTasks: {
          taskType: 0, //任务类型 (0:添加好友任务 1：定时点赞  2:群发任务)
          executionType: 1, //执行类型不能为空
          executeTime: null, //执行时间
          createTime: null,
          intervalTime: null, //执行间隔时间
          satartDate: null, //开始执行时间//定时执行的时候传该值,该值和executeTime保持一致
        },
        applyContent: null, //申请好友用语
      },
      pageList: [],
      addType: true,
    };
  },
  mounted() {
    if (
      this.$route.query != "" &&
      this.$route.query != undefined &&
      this.$route.query != null
    ) {
      if (
        this.$route.query.info != "" &&
        this.$route.query.info != undefined &&
        this.$route.query.info != null
      ) {
        this.addGroupFriend = JSON.parse(this.$route.query.info);
        this.selectList = this.addGroupFriend.wcUserInfoList;
      }
    }
    if (this.$store.state.user.roles.includes("common")) {
      this.common = true;
      this.end = true;
      this.addGroupFriend.wcUserInfoList = [
        {
          wcId: this.$store.state.user.wxid,
          wcName: this.$store.state.user.wcname,
        },
      ];
      this.selectList = this.addGroupFriend.wcUserInfoList;
    }

    if (
      this.selectList == "" ||
      this.selectList == null ||
      this.selectList == undefined
    ) {
      this.addGroupFriend.wcUserInfoList = [
        {
          wcId: this.$store.state.user.wxid,
          wcName: this.$store.state.user.wcname,
        },
      ];
      this.selectList = this.addGroupFriend.wcUserInfoList;
    }
    this.addGroupFriend.wcGroupsUserList = [];
    this.getList();
    this.getPage();
  },
  methods: {
    /** 查询微信群成员列表 */
    getList() {
      this.loading = true;
      //console.log(this.queryParams)
      listWcGroupsUser(this.queryParams).then((res) => {
        if (res["success"]) {
          const dt = res["data"];
          this.total = dt["total"];
          this.wcGroupsUserList = dt["records"];
        }
        this.loading = false;
      });
      setTimeout(() => {
        this.loading = false;
      }, 2000);
    },
    getPage() {
      page({ pageNum: 1, pageSize: 999, termType: 1 }).then((res) => {
        //console.log(res)
        if (res["success"]) {
          const dt = res["data"];
          //this.total = dt["total"];
          this.pageList = dt["records"].map((key) => {
            return { label: key.content, value: key.termId };
          });
          //console.log(this.pageList)
        }
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.pageList;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.label.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      this.addGroupFriend.applyContent = item.label;
    },
    goTs() {},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.show = false;
      this.checkAll = false;
      this.AssistList = [];
      this.selectList = this.addGroupFriend.wcUserInfoList;
      this.ids = [];
      this.$refs.multipleTable.clearSelection();
      this.addGroupFriend = {
        wcUserInfoList: [],
        wcGroupsUserList: [],
        wcTimedTasks: {
          taskType: 0, //任务类型 (0:添加好友任务 1：定时点赞  2:群发任务)
          executionType: 1, //执行类型不能为空
          executeTime: null, //执行时间
          createTime: null,
          intervalTime: null, //执行间隔时间
          satartDate: null, //开始执行时间//定时执行的时候传该值,该值和executeTime保持一致
        },
        applyContent: null, //申请好友用语
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      //console.log(selection)
      this.ids = selection.map((row) => {
        const itemArr = {
          wcId: row.wcId,
          wcGroupId: row.wcGroupId,
          groupUserName: row.groupUserName,
          groupUserId: row.groupUserId,
          groupUserImg: row.groupUserImg,
          groupUserNumber: row.groupUserNumber,
          liveLevel: row.liveLevel,
          addState: 1,
          lastChatTime: row.lastChatTime,
          remark: "",
        };
        return itemArr;
      });
      this.addGroupFriend.wcGroupsUserList = this.ids;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getAssist().then((res) => {
        if (this.addType) {
          if (this.ids != "" && this.ids != null) {
            this.open = true;
          } else {
            this.$message({
              message: "请选择好友！",
              type: "warning",
            });
          }
        } else {
          this.$message({
            message: "添加好友已经超过最高限制！",
            type: "warning",
          });
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getAssist().then((res) => {
        if (this.addType) {
          this.open = true;
          this.addGroupFriend.wcGroupsUserList = [
            {
              wcId: row.wcId,
              wcGroupId: row.wcGroupId,
              groupUserName: row.groupUserName,
              groupUserId: row.groupUserId,
              groupUserImg: row.groupUserImg,
              groupUserNumber: row.groupUserNumber,
              liveLevel: row.liveLevel,
              addState: 1,
              lastChatTime: row.lastChatTime,
              remark: "",
            },
          ];
        } else {
          this.$message({
            message: "添加好友已经超过最高限制！",
            type: "warning",
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      var arr = this.addGroupFriend;
      arr.wcUserInfoList = this.selectList;
      //console.log(arr)
      if (arr.wcUserInfoList.length > 0) {
        var currentTime = moment().format("YYYY-MM-DD HH:mm:ss");
        arr.wcTimedTasks.createTime = currentTime;
        if (arr.wcTimedTasks.executionType == 1) {
          arr.wcTimedTasks.executionTime = currentTime;
          arr.wcTimedTasks.satartDate = currentTime;
        } else {
          arr.wcTimedTasks.executionTime = arr.wcTimedTasks.satartDate;
          if (
            arr.wcTimedTasks.satartDate == "" ||
            arr.wcTimedTasks.satartDate == null
          ) {
            this.$message({
              message: "请选择定时时间！",
              type: "warning",
            });
            return;
          }
        }
        if (arr.applyContent == "" || arr.applyContent == null) {
          this.$message({
            message: "请输入或选择申请好友用语！",
            type: "warning",
          });
          return;
        }
        // if(arr.wcTimedTasks.intervalTime==''||arr.wcTimedTasks.intervalTime==null){
        //       this.$message({
        //           message: '请选择单次间隔！',
        //           type: 'warning'
        //       });
        //       return
        // }
        addGroupUser({
          wcGroupsUserList: arr.wcGroupsUserList,
          wcUserInfoList: arr.wcUserInfoList,
          executionType: arr.wcTimedTasks.executionType,
          wcTimedTasks: {
            createTime: arr.wcTimedTasks.createTime,
            executionType: arr.wcTimedTasks.executionType,
            executionTime: arr.wcTimedTasks.executionTime,
            intervalTime: arr.wcTimedTasks.intervalTime,
            satartDate: arr.wcTimedTasks.satartDate,
            taskType: 0,
          },
          applyContent: arr.applyContent,
        }).then((res) => {
          //console.log(res)
          this.open = false;
          this.$modal.msgSuccess("申请成功");
          if (res.code == 200) {
            this.reset();
          }
        });
      } else {
        this.$message({
          message: "请选择助手！",
          type: "warning",
        });
      }
    },
    search() {
      // if(this.query.wcName!=null&&this.query.wcName!=''){
      //   this.show=true
      //   this.getAssist()
      // }else{
      //   this.$message({
      //       message: '请先输入要搜索的内容！',
      //       type: 'warning'
      //   });
      // }
      this.show = true;
      this.getAssist()
    },
    async getAssist() {
      await listWcAssist(this.query).then((res) => {
        if (res["success"]) {
          const dt = res["data"];
          this.totals = dt["total"];
          dt["records"].forEach((element) => {
            element.remark = false;
          });
          this.AssistList = dt["records"];
          if (this.$store.state.user.roles.includes("common")) {
            this.addType = dt["records"][0].canCreateTask;
          }
          if (this.selectList != "" && this.selectList != null) {
            this.AssistList.forEach((item) => {
              this.selectList.forEach((arr, index) => {
                if (item.wcId == arr.wcId && item.canCreateTask) {
                  item.remark = true;
                } else if (item.wcId == arr.wcId && !item.canCreateTask) {
                  this.selectList.splice(index, 1);
                }
              });
            });
            this.addGroupFriend.wcUserInfoList = this.selectList;
          }
        }
      });
    },
    handleCheckAllChange(selection) {
      if (this.AssistList != null && this.AssistList != "") {
        this.checkAll = selection;
        if (selection) {
          this.selectList = this.AssistList.map((item) => {
            const newItem = {
              assistId: item.assistId,
              wcId: item.wcId,
              wcName: item.wcName,
              wcNumber: item.wcNumber,
              wcImg: item.wcImg,
              wcPhone: item.wcPhone,
              region: item.region,
              loginTime: item.loginTime,
              loginState: 1,
              olState: 1,
              remark: "",
            };
            return newItem;
          });
          this.AssistList.forEach((element) => {
            element.remark = true;
          });
        } else {
          this.selectList = [];
          this.AssistList.forEach((element) => {
            element.remark = false;
          });
        }
      } else {
        this.checkAll = false;
        this.$message({
          message: "请先搜索助手！",
          type: "warning",
        });
      }

      // this.ids = selection.map(item => item.id)
      // this.single = selection.length!==1
      // this.multiple = !selection.length
    },
    setIdx(idx, type) {
      if (!type) {
        this.AssistList[idx].remark = true;
        var item = this.AssistList[idx];
        //console.log(this.selectList)
        this.selectList.push({
          assistId: item.assistId,
          wcId: item.wcId,
          wcName: item.wcName,
          wcNumber: item.wcNumber,
          wcImg: item.wcImg,
          wcPhone: item.wcPhone,
          region: item.region,
          loginTime: item.loginTime,
          loginState: 1,
          olState: 1,
          remark: "",
        });
      }
    },
    delIdx(idx, id) {
      this.checkAll = false;
      this.selectList.splice(idx, 1);
      this.AssistList.forEach((element) => {
        if (element.wcId == id) {
          element.remark = false;
        }
      });
    },
  },
};

/** js请求 调用 */

// 查询微信群成员列表
export function listWcGroupsUser(query) {
  return request({
    url: "/arbit/wcgroups_user/page",
    method: "get",
    params: query,
  });
}
// 查询助手信息列表
export function listWcAssist(query) {
  return request({
    url: "/arbit/wcuser_info/page",
    method: "get",
    params: query,
  });
}
// 群好友添加
export function addGroupUser(query) {
  return request({
    url: "/arbit/wctimedTasks/addGroupFriends",
    method: "POST",
    data: query,
  });
}
// 查询助手招呼语设置列表
export function page(query) {
  return request({
    url: "/wcUserTerms/page",
    method: "get",
    params: query,
  });
}
</script>
<style lang="scss">
.my-autocomplete {
  width: 370px;
  li {
    line-height: normal;
    padding: 7px;

    .name {
      white-space: normal;
      overflow: auto;
      line-height: 30px;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
<style lang="scss">
.app-container {
  background-color: #f6f9fb;
}
.frominfo {
  display: flex;
  background-color: #fff;
  padding: 10px;
  padding-bottom: 0;
  margin-bottom: 20px;
  .from-item {
    display: flex;
    flex-wrap: wrap;
    width: 80%;
  }
  .from-Btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 20%;
  }
}
.mb8 {
  margin-bottom: 20px;
}
.blue-button {
  color: #fff;
  background-color: #0078fb;
  border-color: #0078fb;
}
.box-txt {
  font-size: 14px;
  margin-right: 10px;
  line-height: 40px;
}
.dia-box {
  margin-top: -20px;
  padding: 0 20px 20px 20px;
  display: flex;
  flex-direction: column;
  .dia-box-search {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .select-all {
      border: 1px solid #dcdfe6;
      height: 36px;
      line-height: 36px;
      padding: 0 10px;
      border-radius: 4px;
    }
  }
  .dia-box-time {
    display: flex;
    flex-direction: column;
    .box-setup {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
    .box-setups {
      display: flex;
      margin-bottom: 20px;
    }
  }
  .dia-box-lable {
    width: 90%;
    border-radius: 5px;
    border: 1px solid #eee;
    min-height: 100px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    margin-bottom: 20px;
    .lable-box {
      padding: 0 5px;
      height: 20px;
      line-height: 20px;
      margin-right: 10px;
      border: 1px solid #dcdcdc;
      background-color: #ebf4ff;
      font-size: 12px;
      border-radius: 3px;
    }
    .select {
      color: #fff;
      background-color: #4095e5;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: center;
  }
}
</style>
